/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package modules.enderecamento.models.dao;

/**
 *
 * @author Clezio
 */
import java.util.ArrayList;
import java.util.List;
import modules.enderecamento.models.dto.Cliente;
import modules.enderecamento.util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;
   
 public class ClienteDAO{  
     
     private SessionFactory sessionFactory;
     
     public ClienteDAO() throws Exception{
         sessionFactory = HibernateUtil.getSessionFactory();
     }
       
     public void save(Cliente cliente) throws ConstraintViolationException, Exception{
         Session session = sessionFactory.openSession();
         Transaction tx = session.beginTransaction();
         try{
             if(cliente.getId() > 0){
                session.update(cliente);
             }else{
                session.save(cliente);
             }
         }catch(ConstraintViolationException e){
             throw e;
         }catch(Exception e){
             throw e;
         }
         session.flush();
         tx.commit();
         session.close();  
     }  
       
     public java.util.List<Cliente> getList(String condicao) throws Exception{
         Session session = sessionFactory.openSession();
         Query query = session.createQuery(condicao);
         List clientes = new ArrayList(query.list());
         session.flush();  
         session.close();  
         return clientes;
     }  
       
     public Cliente retrieve(Integer pk) throws Exception{
         Session session = sessionFactory.openSession();
         Cliente cliente = (Cliente)session.load(Cliente.class, pk);
         Cliente clienteDTO = mountDto(cliente);
         session.flush();
         session.close();  
         return clienteDTO;
     }  
       
     public void delete(Cliente cliente) throws Exception{
         Session session = sessionFactory.openSession();
         Transaction tx = session.beginTransaction();
         session.delete(cliente);
         session.flush();
         tx.commit();
         session.close();  
     }

    public Cliente mountDto(Cliente cliente) {
        Cliente clienteDTO = new Cliente();
        clienteDTO.setId(cliente.getId());
        clienteDTO.setNome(cliente.getNome());
        clienteDTO.setRazaoSocial(cliente.getRazaoSocial());
        clienteDTO.setCnpj(cliente.getCnpj());
        clienteDTO.setAtivo(cliente.isAtivo());
        return clienteDTO;
    }
 }